﻿#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <locale.h>

#include <glib.h>
#include <glib-object.h>

#include "http.h"

//pkg-config --modversion glib-2.0
//http://ftp.gnome.org/pub/gnome/binaries/win32/
//http://sourceforge.net/projects/gnuwin32/files/
int main(int argc, char *argv[]) {
	GMainLoop *loop = NULL;

	setlocale(LC_ALL, "");
	setbuf(stdout, NULL);

	g_type_init();

	if (!g_thread_supported()) {
		g_thread_init(NULL);
	}

	gint port = 0;
	gchar *name = NULL;
	GOptionEntry options[] = { { "port", 'p', G_OPTION_FLAG_IN_MAIN, G_OPTION_ARG_INT, &port, "Set server port", NULL }, { "name", 'n', G_OPTION_FLAG_IN_MAIN,
			G_OPTION_ARG_STRING, &name, "Set server name", NULL }, { NULL } };

	GError *err = NULL;
	GOptionContext *context = g_option_context_new(NULL);
	g_option_context_set_help_enabled(context, TRUE);
	g_option_context_set_ignore_unknown_options(context, TRUE);
	g_option_context_add_main_entries(context, options, NULL);
	if (!g_option_context_parse(context, &argc, &argv, &err)) {
		if (err != NULL) {
			g_printerr("%s\n", err->message);
			g_error_free(err);
		} else {
			g_printerr("An unknown error occurred.\n");
		}
		exit(EXIT_FAILURE);
	}
	g_option_context_free(context);

	if (port == 0) {
		g_printerr("Please set the server port.\n");
		exit(EXIT_FAILURE);
	}

	if (!http_start(port, name)) {
		g_setenv("TZ", "CCT", TRUE);

		printf("%s\n", "JSON-RPC Started...");
		loop = g_main_loop_new(NULL, TRUE);
		g_main_loop_run(loop);
	} else {
		g_printerr("Port %d is in use.\n", port);
	}

	return EXIT_SUCCESS;
}
